using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BuildPlane : MonoBehaviour
{
    public int setX;

    public int setY;

    private Mesh mesh;
    // private void OnDrawGizmos () {
    //     if (vect == null) {
    //         return;
    //     }
    //     Gizmos.color = Color.black;
    //     for (int i = 0; i < vect.Length; i++) {
    //         Gizmos.DrawSphere(vect[i], 0.05f);
    //     }
    //
    //     buildMesh();
    // }

    private Vector3[] vect;
    private Vector2[] uv;
    void Start()
    {
        vect=new Vector3[setX*setY];
        uv = new Vector2[vect.Length];
        for (int i = 0, y = 0; y < setY; y++)
        {
            for (int x = 0; x < setX; x++,i++)
            {
                vect[i]=new Vector3(x,y);
                uv[i] = new Vector2((float)x / setX,(float) y / setY);
            }
            
        }
        buildMesh();
    }

    private void buildMesh()
    {
        GetComponent<MeshFilter>().mesh=mesh=new Mesh();
        //mesh.name = "Plane";
        mesh.vertices = vect;
        mesh.uv = uv;
        int[] triangles =new int[setX*setY*6];

        for (int j = 1, i = 0, num = 0; j < setY ;j++,num++)
        {
            for (int x=0; x < setX-1; i+=6,num++,x++)
            {
                triangles[i] = num;
                triangles[i+1] = triangles[i+4]=j*setX+x;
                triangles[i+2] = triangles[i+3]=num+1;
                triangles[i+5] = j*setX + x + 1;
            }
        }
        mesh.triangles = triangles;
        mesh.RecalculateNormals();
    }
}
